# 数据库操作工具
import pymysql
from tests.utils.log_utils import LogUtils

logger = LogUtils.get_logger()


class DBUtils:
    def __init__(self):
        self.connection = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='password',
            db='test_db',
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor
        )

    def create_test_user(self):
        """创建测试用户"""
        with self.connection.cursor() as cursor:
            sql = "INSERT INTO users (name, certified) VALUES (%s, %s)"
            cursor.execute(sql, ('test_user', 1))
            user_id = cursor.lastrowid
            self.connection.commit()
            logger.info("创建测试用户成功")
        return user_id

    def create_order(self, user_id, amount, activity=None):
        """创建测试订单"""
        with self.connection.cursor() as cursor:
            sql = "INSERT INTO orders (user_id, amount, activity) VALUES (%s, %s, %s)"
            cursor.execute(sql, (user_id, amount, activity))
            order_id = cursor.lastrowid
            self.connection.commit()
        return order_id

    def clear_test_data(self):
        """清理测试数据"""
        with self.connection.cursor() as cursor:
            cursor.execute("DELETE FROM orders WHERE user_id LIKE 'test_user%'")
            cursor.execute("DELETE FROM users WHERE name LIKE 'test_user%'")
            self.connection.commit()
        logger.info("测试数据清理完成")

